package com.example.blog1.utils;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

import java.security.Key;
import java.util.Date;
import java.util.Map;

@Slf4j
public class JwtUtil {
    //设置令牌的过期时间为30分钟
    private static final long expiration = 1000 * 60 * 30;
    //密钥
    private static final String secretString = "2wx3qTP4mDaqkC2gycnyQzS4InxosMpwqph0zh8ccwM=";
    //生成安全密钥
    private static final Key key = Keys.hmacShaKeyFor(Decoders.BASE64URL.decode(secretString));

    public static String genJwt(Map<String,Object> claim) {
        String jwt = Jwts.builder()
                .setClaims(claim) //自定义内容（负载）
                .setIssuedAt(new Date()) //设置签证时间
                .setExpiration(new Date(System.currentTimeMillis() + expiration)) //设置过期时间
                .signWith(key) //签名算法
                .compact();

        return jwt;
    }

    public static Claims parseJwt(String token) {
        if (token == null || "null".equals(token)) return null;
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims claims = null;
        try {
            claims = build.parseClaimsJws(token).getBody();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("解析token失败，token:" + token);
        }
        return claims;
    }

    public static Integer getUserIdFromToken(String token) {
        Claims claims = JwtUtil.parseJwt(token);
        if (claims == null) return null;
        return (Integer) claims.get("id");
    }
}
